// 引入接口文件
import { getUseDetail, getMonthData } from './couponReportServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'

// 初始默认状态
const defultState = {
  loading: false,
  btnLoading: false,
	couponsConfigId: '',
	detail: [],
	tableQuery: {
		startDate: moment().format('YYYY-MM-DD'),
		endDate: moment().format('YYYY-MM-DD')
	},
	tableMonthDetail: []
}

// 声明module
const tmpModule = {
	// 默认状态
	state: cloneDeep(defultState),
	// 入口函数(先执行)
	subscriptions: {
		setup({ dispatch, history }) {
			history.listen(({ pathname, query }) => {
				// 页面路由匹配时执行
				if ('' + tmpModule.pathname === '' + pathname) {
					dispatch({ type: 'updateStore', payload: { couponsConfigId: query.couponsConfigId } })
					dispatch({ type: 'getUseDetail', payload: { params: { couponsConfigId: query.couponsConfigId } } })
					dispatch({ type: 'getMonthData', payload: { params: { couponsConfigId: query.couponsConfigId, ...defultState.tableQuery } } })
				}
			})
		},
	},

	// 方法列表
	effects: {
		// 使用概况
		*getUseDetail({ payload }, { put, call, select }) {
			try {
				let state = yield select(state => state[tmpModule.namespace])
				const { data, success, msg } = yield call(getUseDetail, payload.params)
				if (success) {
					yield put({
						type: 'updateStore',
						payload: {
							detail: data ? [{ key: 1, ...data }] : []
						}
					})
				}
			} catch (e) {
				console.error(e)
			}
		},
		// 月度分析
		*getMonthData({ payload }, { put, call, select }) {
			try {
				let state = yield select(state => state[tmpModule.namespace])
        yield put({ type: 'updateStore', payload: { loading: true,btnLoading: true, } })
				const { data, success, msg } = yield call(getMonthData, payload.params)
        yield put({ type: 'updateStore', payload: { loading: false,btnLoading: false, } })
        
        if (success) {
					yield put({
						type: 'updateStore',
						payload: {
							tableMonthDetail: data
						}
					})
				}
			} catch (e) {
				console.error(e)
			}
		},

		*resetMonth({ payload }, { put, call, select }) {
			yield put({
				type: 'updateStore',
				payload: {
					tableQuery: {
						startDate: moment().format('YYYY-MM-DD'),
						endDate: moment().format('YYYY-MM-DD')
					}
				}
			})
			setTimeout(() => {
				payload.cb()
			}, 0)
		},

		*searchData({ payload }, { put, call, select }) {
			let state = yield select(state => state[tmpModule.namespace])
			yield put({
				type: 'getMonthData',
				payload: {
					params: {
						couponsConfigId: state.couponsConfigId,
						...state.tableQuery
					}
				}
			})
		},

	},

	// 存入状态机
	reducers: {
		updateStore(preState, action) {
			return Object.assign({}, preState, action.payload)
		},
	}
}

export default tmpModule
